package com.ruoyi.ftrl.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.ftrl.domain.Dto.HeiMaYi;
import com.ruoyi.ftrl.domain.Dto.Response;
import com.ruoyi.ftrl.domain.EquipmentDocking;
import com.ruoyi.ftrl.domain.EquipmentInfo;
import com.ruoyi.ftrl.domain.RoomInfo;
import com.ruoyi.ftrl.domain.TemperatureInfo;
import com.ruoyi.ftrl.mapper.EquipmentDockingMapper;
import com.ruoyi.ftrl.mapper.EquipmentInfoMapper;
import com.ruoyi.ftrl.mapper.RoomInfoMapper;
import com.ruoyi.ftrl.service.IEquipmentDockingService;
import com.ruoyi.ftrl.service.ITemperatureInfoService;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 物联网平台拉取室温采集数据信息Controller
 *
 * @author dihang
 * @date 2024-07-16
 */
@RestController
public class EquipmentsController extends BaseController {
    @Autowired
    private ITemperatureInfoService temperatureInfoService;
    @Autowired
    private IEquipmentDockingService equipmentDockingService;
    @Autowired
    EquipmentDockingMapper equipmentDockingMapper;
    @Autowired
    private EquipmentInfoMapper equipmentInfoMapper;
    @Autowired
    private RoomInfoMapper roomInfoMapper;

    @PostMapping("/receiveData")
    public void receiveData(@RequestBody String payload) {
//    // 给定的包含JSON数据的字符串
//      payload = "Received data: {\"upPacketSN\":-1,\"upDataSN\":-1,\"topic\":\"v1/up/ad\",\"timestamp\":1720146587538,\"tenantId\":\"2000499359\",\"serviceId\":\"\",\"protocol\":\"lwm2m\",\"productId\":\"17106951\",\"payload\":{\"APPdata\":\"AADk/v7+aEaUVHNZIDJhgdSQIAEAADgmAAAAADgmAAAAAFgJAAAAAAAAAAAAAAA4KQkWByQHAAAAAHImAAAAWCcAAABYJwAAAFUnAAAAVScAAABTJwAAAFQnAAAAUycAAABVJwAAAEcnAAAAQycAAAA4JwAAACQnAAAAEicAAABxJgAAAGYlAAAAGCUAAAAYJQAAABglAAAAGCUAAAAYJQAAABglAAAAGCUAAAAYJQAAAHElADwAPAA8PAAQABAAAAAAAAEIAJMEciZgISMRhomUVHNZIDJhCAAALQMOAAEA//8uuFwW\"},\"messageType\":\"dataReport\",\"deviceType\":\"\",\"deviceId\":\"78d20a8165c946a281f5a9507bcb78de\",\"assocAssetId\":\"\",\"IMSI\":\"undefined\",\"IMEI\":\"861322059735494\"}";
        // 处理设备上传的数据，这里payload是接收到的原始密文数据
        System.out.println("Received data: " + payload);
//        String jsonString =payload;
        // 去掉前缀 "Received data: "来得到有效的JSON字符串
//        String jsonSubstring = payload.substring(payload.indexOf("{"));

//        try {
//            // 创建ObjectMapper实例
//            ObjectMapper mapper = new ObjectMapper();
//
//            // 解析JSON字符串到JsonNode对象
//            JsonNode rootNode = mapper.readTree(jsonSubstring);
//
//            // 获取"payload"对象
//            JsonNode payloadNode = rootNode.path("payload");
//
//            // 提取"APPdata"字段的值
//            JsonNode serviceDataNode = rootNode.path("payload").path("serviceData");
//            String appDataBase64 = serviceDataNode.path("uData").asText();
//            System.out.println("密文数据为："+appDataBase64);
//
//            // 对Base64编码字符串进行解码
//            byte[] decodedBytes = Base64.getDecoder().decode(appDataBase64);
//
//            // 将解码后的字节数组转换为16进制字符串
//            StringBuilder hexString = new StringBuilder();
//            for (byte b : decodedBytes) {
//                hexString.append(String.format("%02X", b));
//            }
//            //该字符串为解密后的16进制编码
//            String s = hexString.toString();
//
//            // 输出解码后的16进制字符串
//            System.out.println("解码后的16进制字符串: " + hexString.toString());
        StringBuilder hexString = new StringBuilder();
        try {
            // 创建 ObjectMapper 实例
            ObjectMapper mapper = new ObjectMapper();

            // 解析 JSON 字符串到 JsonNode 对象
            JsonNode rootNode = mapper.readTree(payload);

            String imei = rootNode.path("IMEI").asText();
            System.out.println("IMEI: " + imei);

            // 获取 "payload" 节点
            JsonNode payloadNode = rootNode.path("payload");

            // 检查 payload 是对象还是数组
            if (payloadNode.isObject()) {
                // 处理对象类型的 payload
                JsonNode serviceDataNode = payloadNode.path("serviceData");
                String appDataBase64 = serviceDataNode.path("uData").asText(null);

                if (appDataBase64 == null || appDataBase64.isEmpty()) {
                    System.err.println("uData 字段为空或丢失");
                }

                System.out.println("密文数据为：" + appDataBase64);

                // 对 Base64 编码字符串进行解码
                try {
                    byte[] decodedBytes = Base64.getDecoder().decode(appDataBase64);

                    // 将解码后的字节数组转换为16进制字符串
//                    StringBuilder hexString = new StringBuilder();
                    for (byte b : decodedBytes) {
                        hexString.append(String.format("%02X", b));
                    }

                    // 输出解码后的16进制字符串
                    System.out.println("解码后的16进制字符串: " + hexString.toString());
                } catch (IllegalArgumentException e) {
                    System.err.println("Base64 解码失败: " + e.getMessage());
                }
            } else if (payloadNode.isArray()) {
                // 处理数组类型的 payload
                for (JsonNode node : payloadNode) {
                    JsonNode serviceDataNode = node.path("serviceData");
                    String appDataBase64 = serviceDataNode.path("uData").asText(null);

                    if (appDataBase64 == null || appDataBase64.isEmpty()) {
                        System.err.println("uData 字段为空或丢失");
                        continue;
                    }

                    System.out.println("密文数据为：" + appDataBase64);

                    // 对 Base64 编码字符串进行解码
                    try {
                        byte[] decodedBytes = Base64.getDecoder().decode(appDataBase64);

                        // 将解码后的字节数组转换为16进制字符串

                        for (byte b : decodedBytes) {
                            hexString.append(String.format("%02X", b));
                        }

                        // 输出解码后的16进制字符串
                        System.out.println("解码后的16进制字符串: " + hexString.toString());
                    } catch (IllegalArgumentException e) {
                        System.err.println("Base64 解码失败: " + e.getMessage());
                    }
                }
            } else {
                System.err.println("Unexpected payload structure.");
            }
            //创建对象
            TemperatureInfo temperatureInfo = new TemperatureInfo();
            EquipmentDocking equipmentDockingInfo = new EquipmentDocking();
            // 输出解码后的16进制字符串
            //解码规则
//            System.out.println("解码后的16进制字符串: " + hexString.toString());
            String string = hexString.toString();
            String s0 = string.substring(6, 8) + string.substring(8, 10);
            System.out.println("仪表类型为：" + s0);
            equipmentDockingInfo.setMeterType(s0);

            String s1 = string.substring(24, 26) + string.substring(22, 24) + string.substring(20, 22) + string.substring(18, 20) + string.substring(16, 18);
            System.out.println("仪表编号为：" + s1);
            //设备ID
            equipmentDockingInfo.setNodeId(imei);

            String s3 = string.substring(28, 30) + string.substring(26, 28);
            System.out.println("厂家代码为：" + s3);
            equipmentDockingInfo.setManufactorCode(s3);

            String s4 = string.substring(40, 42) + "." + string.substring(38, 40);
            if (string.charAt(40) == '0') {
                s4 = s4.substring(1, 5);
            }
            BigDecimal bigDecimalValue = new BigDecimal(s4);
            System.out.println("当前室内温度为：" + s4 + "℃");
            equipmentDockingInfo.setTemp(bigDecimalValue);

            String s5 = string.substring(50, 52) + "." + string.substring(48, 50);
            if (string.charAt(50) == '0') {
                s5 = s5.substring(1, 5);
            }
            System.out.println("电池电压为：" + s5);
            BigDecimal bigDecimal = new BigDecimal(s5);
            equipmentDockingInfo.setVoltage(bigDecimal);

            String s6 = string.substring(58, 60) + "." + string.substring(56, 58);
            if (string.charAt(58) == '0') {
                s6 = s6.substring(1, 5);
            }
//        System.out.println("当前室内温度(重复)为："+s6+"℃");
//        BigDecimal bigDecimal1 = new BigDecimal(s6);
//        equipmentDockingInfo.setTemperature1(bigDecimal1);

            String s7 = string.substring(74, 76) + string.substring(72, 74) + string.substring(70, 72) + string.substring(68, 70);
            s7 = s7.replaceAll("^0+", "");
            System.out.println("累积上电时间为：" + s7 + "分钟");
            equipmentDockingInfo.setPowerOn(s7);

            String s8 = string.substring(92, 94);
            s8 = String.valueOf(Integer.parseInt(s8, 16));
            System.out.println("当前室内湿度为：" + s8);
            equipmentDockingInfo.setHumidity(s8);

//            String s9 = string.substring(104, 106) + string.substring(102, 104) + string.substring(100, 102) + string.substring(98, 100) + string.substring(96, 98) + string.substring(94, 96);
//            // 解析字符串为 LocalDateTime 对象
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMddHHmmss");
//            LocalDateTime dateTime = LocalDateTime.parse(s9, formatter);
//            // 格式化为指定的时间字符串
//            DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//            s9 = dateTime.format(outputFormatter);
//            System.out.println("实际时间为：" + s9);
//            Instant instant = dateTime.atZone(ZoneId.systemDefault()).toInstant();
//            // 转换为 Date
//            Date date = Date.from(instant);
//            equipmentDockingInfo.setTime(date);
            //上报时间
            equipmentDockingInfo.setTime(new Date());

            String s10 = string.substring(106, 108);
            s10 = s10.replaceAll("^0+", "");
            System.out.println("上一次信号强度为：" + s10);
            equipmentDockingInfo.setSignalIntensity(s10);

            String s11 = string.substring(110, 112) + string.substring(108, 110);
            System.out.println("ST状态为：" + s11);
            equipmentDockingInfo.setStState(s11);

            String s12 = string.substring(118, 120) + "." + string.substring(116, 118);
            System.out.println("前0-1小时室内平均温度为：" + s12 + "℃");
            BigDecimal decimal1 = new BigDecimal(s12);
            equipmentDockingInfo.setOneHeat(decimal1);

            String s13 = string.substring(120, 122);
            s13 = String.valueOf(Integer.parseInt(s13, 16));
            System.out.println("前0-1小时湿度为：" + s13);
            equipmentDockingInfo.setOneHumidity(s13);

            String s14 = string.substring(128, 130) + "." + string.substring(126, 128);
            System.out.println("前1-2小时室内平均温度为：" + s14 + "℃");
            BigDecimal bigDecimal2 = new BigDecimal(s14);
            equipmentDockingInfo.setTwoHeat(bigDecimal2);

            String s15 = string.substring(130, 132);
            s15 = String.valueOf(Integer.parseInt(s15, 16));
            System.out.println("前1-2小时湿度为：" + s15);
            equipmentDockingInfo.setTwoHumidity(s15);

            String s16 = string.substring(138, 140) + "." + string.substring(136, 138);
            System.out.println("前2-3小时室内平均温度为：" + s16 + "℃");
            BigDecimal bigDecimal3 = new BigDecimal(s16);
            equipmentDockingInfo.setThreeHeat(bigDecimal3);

            String s17 = string.substring(142, 144);
            s17 = String.valueOf(Integer.parseInt(s17, 16));
            System.out.println("前2-3小时湿度为：" + s17);
            equipmentDockingInfo.setThreeHumidity(s17);

            String s18 = string.substring(148, 150) + "." + string.substring(146, 148);
            System.out.println("前3-4小时室内平均温度为：" + s18 + "℃");
            BigDecimal bigDecimal4 = new BigDecimal(s18);
            equipmentDockingInfo.setFourHeat(bigDecimal4);

            String s19 = string.substring(150, 152);
            s19 = String.valueOf(Integer.parseInt(s19, 16));
            System.out.println("前3-4小时湿度为：" + s19);
            equipmentDockingInfo.setFourHumidity(s19);

            String s20 = string.substring(158, 160) + "." + string.substring(156, 158);
            System.out.println("前4-5小时室内平均温度为：" + s20 + "℃");
            BigDecimal bigDecimal5 = new BigDecimal(s20);
            equipmentDockingInfo.setFiveHeat(bigDecimal5);

            String s21 = string.substring(160, 162);
            s21 = String.valueOf(Integer.parseInt(s21, 16));
            System.out.println("前4-5小时湿度为：" + s21);
            equipmentDockingInfo.setFiveHumidity(s21);

            String s22 = string.substring(168, 170) + "." + string.substring(166, 168);
            System.out.println("前5-6小时室内平均温度为：" + s22 + "℃");
            BigDecimal bigDecimal6 = new BigDecimal(s22);
            equipmentDockingInfo.setSixHeat(bigDecimal6);

            String s23 = string.substring(170, 172);
            s23 = String.valueOf(Integer.parseInt(s23, 16));
            System.out.println("前5-6小时湿度为：" + s23);
            equipmentDockingInfo.setSixHumidity(s23);

            String s24 = string.substring(178, 180) + "." + string.substring(176, 178);
            System.out.println("前6-7小时室内平均温度为：" + s24 + "℃");
            BigDecimal bigDecimal7 = new BigDecimal(s24);
            equipmentDockingInfo.setSevenHeat(bigDecimal7);

            String s25 = string.substring(180, 182);
            s25 = String.valueOf(Integer.parseInt(s25, 16));
            System.out.println("前6-7小时湿度为：" + s25);
            equipmentDockingInfo.setSevenHumidity(s25);

            String s26 = string.substring(188, 190) + "." + string.substring(186, 188);
            System.out.println("前7-8小时室内平均温度为：" + s26 + "℃");
            BigDecimal bigDecimal8 = new BigDecimal(s26);
            equipmentDockingInfo.setEightHeat(bigDecimal8);

            String s27 = string.substring(190, 192);
            s27 = String.valueOf(Integer.parseInt(s27, 16));
            System.out.println("前7-8小时湿度为：" + s27);
            equipmentDockingInfo.setEightHumidity(s27);

            String s28 = string.substring(198, 200) + "." + string.substring(196, 198);
            System.out.println("前8-9小时室内平均温度为：" + s28 + "℃");
            BigDecimal bigDecimal9 = new BigDecimal(s28);
            equipmentDockingInfo.setNineHeat(bigDecimal9);

            String s29 = string.substring(200, 202);
            s29 = String.valueOf(Integer.parseInt(s29, 16));
            System.out.println("前8-9小时湿度为：" + s29);
            equipmentDockingInfo.setNineHumidity(s29);

            String s30 = string.substring(208, 210) + "." + string.substring(206, 208);
            System.out.println("前9-10小时室内平均温度为：" + s30 + "℃");
            BigDecimal bigDecimal10 = new BigDecimal(s30);
            equipmentDockingInfo.setTenHeat(bigDecimal10);

            String s31 = string.substring(210, 212);
            s31 = String.valueOf(Integer.parseInt(s31, 16));
            System.out.println("前9-10小时湿度为：" + s31);
            equipmentDockingInfo.setTenHumidity(s31);

            String s32 = string.substring(218, 220) + "." + string.substring(216, 218);
            System.out.println("前10-11小时室内平均温度为：" + s32 + "℃");
            BigDecimal bigDecimal11 = new BigDecimal(s32);
            equipmentDockingInfo.setElevenHeat(bigDecimal11);

            String s33 = string.substring(220, 222);
            s33 = String.valueOf(Integer.parseInt(s33, 16));
            System.out.println("前10-11小时湿度为：" + s33);
            equipmentDockingInfo.setElevenHumidity(s33);

            String s34 = string.substring(228, 230) + "." + string.substring(226, 228);
            System.out.println("前11-12小时室内平均温度为：" + s34 + "℃");
            BigDecimal bigDecimal12 = new BigDecimal(s34);
            equipmentDockingInfo.setTwelveHeat(bigDecimal12);

            String s35 = string.substring(230, 232);
            s35 = String.valueOf(Integer.parseInt(s35, 16));
            System.out.println("前11-12小时湿度为：" + s35);
            equipmentDockingInfo.setTwelveHumidity(s35);

            String s36 = string.substring(238, 240) + "." + string.substring(236, 238);
            System.out.println("前12-13小时室内平均温度为：" + s36 + "℃");
            BigDecimal bigDecimal13 = new BigDecimal(s36);
            equipmentDockingInfo.setThirteenHeat(bigDecimal13);

            String s37 = string.substring(240, 242);
            s37 = String.valueOf(Integer.parseInt(s37, 16));
            System.out.println("前12-13小时湿度为：" + s37);
            equipmentDockingInfo.setThirteenHumidity(s37);

            String s38 = string.substring(248, 250) + "." + string.substring(246, 248);
            System.out.println("前13-14小时室内平均温度为：" + s38 + "℃");
            BigDecimal bigDecimal14 = new BigDecimal(s38);
            equipmentDockingInfo.setFourteenHeat(bigDecimal14);

            String s39 = string.substring(250, 252);
            s39 = String.valueOf(Integer.parseInt(s39, 16));
            System.out.println("前13-14小时湿度为：" + s39);
            equipmentDockingInfo.setFourteenHumidity(s39);

            String s40 = string.substring(258, 260) + "." + string.substring(256, 258);
            System.out.println("前14-15小时室内平均温度为：" + s40 + "℃");
            BigDecimal bigDecimal15 = new BigDecimal(s40);
            equipmentDockingInfo.setFifteenHeat(bigDecimal15);

            String s41 = string.substring(260, 262);
            s41 = String.valueOf(Integer.parseInt(s41, 16));
            System.out.println("前14-15小时湿度为：" + s41);
            equipmentDockingInfo.setFifteenHumidity(s41);

            String s42 = string.substring(268, 270) + "." + string.substring(266, 268);
            System.out.println("前15-16小时室内平均温度为：" + s42 + "℃");
            BigDecimal bigDecimal16 = new BigDecimal(s42);
            equipmentDockingInfo.setSixteenHeat(bigDecimal16);

            String s43 = string.substring(270, 272);
            s43 = String.valueOf(Integer.parseInt(s43, 16));
            System.out.println("前15-16小时湿度为：" + s43);
            equipmentDockingInfo.setSixteenHumidity(s43);

            String s44 = string.substring(278, 280) + "." + string.substring(276, 278);
            System.out.println("前16-17小时室内平均温度为：" + s44 + "℃");
            BigDecimal bigDecimal17 = new BigDecimal(s44);
            equipmentDockingInfo.setSeventeenHeat(bigDecimal17);

            String s45 = string.substring(280, 282);
            s45 = String.valueOf(Integer.parseInt(s45, 16));
            System.out.println("前16-17小时湿度为：" + s45);
            equipmentDockingInfo.setSeventeenHumidity(s45);

            String s46 = string.substring(288, 290) + "." + string.substring(286, 288);
            System.out.println("前17-18小时室内平均温度为：" + s46 + "℃");
            BigDecimal bigDecimal18 = new BigDecimal(s46);
            equipmentDockingInfo.setEighteenHeat(bigDecimal18);

            String s47 = string.substring(290, 292);
            s47 = String.valueOf(Integer.parseInt(s47, 16));
            System.out.println("前17-18小时湿度为：" + s47);
            equipmentDockingInfo.setEighteenHumidity(s47);

            String s48 = string.substring(298, 300) + "." + string.substring(296, 298);
            System.out.println("前18-19小时室内平均温度为：" + s48 + "℃");
            BigDecimal bigDecimal19 = new BigDecimal(s48);
            equipmentDockingInfo.setNineteenHeata(bigDecimal19);

            String s49 = string.substring(300, 302);
            s49 = String.valueOf(Integer.parseInt(s49, 16));
            System.out.println("前18-19小时湿度为：" + s49);
            equipmentDockingInfo.setNineteenHumidity(s49);

            String s50 = string.substring(308, 310) + "." + string.substring(306, 308);
            System.out.println("前19-20小时室内平均温度为：" + s50 + "℃");
            BigDecimal bigDecimal20 = new BigDecimal(s50);
            equipmentDockingInfo.setTwentyHeat(bigDecimal20);

            String s51 = string.substring(310, 312);
            s51 = String.valueOf(Integer.parseInt(s51, 16));
            System.out.println("前19-20小时湿度为：" + s51);
            equipmentDockingInfo.setTwentyHumidity(s51);

            String s52 = string.substring(318, 320) + "." + string.substring(316, 318);
            System.out.println("前20-21小时室内平均温度为：" + s52 + "℃");
            BigDecimal bigDecimal21 = new BigDecimal(s52);
            equipmentDockingInfo.setTwentyOneHeat(bigDecimal21);

            String s53 = string.substring(320, 322);
            s53 = String.valueOf(Integer.parseInt(s53, 16));
            System.out.println("前20-21小时湿度为：" + s53);
            equipmentDockingInfo.setTwentyOneHumidity(s53);

            String s54 = string.substring(328, 330) + "." + string.substring(326, 328);
            System.out.println("前21-22小时室内平均温度为：" + s54 + "℃");
            BigDecimal bigDecimal22 = new BigDecimal(s54);
            equipmentDockingInfo.setTwentyTwoHeat(bigDecimal22);

            String s55 = string.substring(330, 332);
            s55 = String.valueOf(Integer.parseInt(s55, 16));
            System.out.println("前21-22小时湿度为：" + s55);
            equipmentDockingInfo.setTwentyTwoHumidity(s55);

            String s56 = string.substring(338, 340) + "." + string.substring(336, 338);
            System.out.println("前22-23小时室内平均温度为：" + s56 + "℃");
            BigDecimal bigDecimal23 = new BigDecimal(s56);
            equipmentDockingInfo.setTwentyThreeHeat(bigDecimal23);

            String s57 = string.substring(340, 342);
            s57 = String.valueOf(Integer.parseInt(s57, 16));
            System.out.println("前22-23小时湿度为：" + s57);
            equipmentDockingInfo.setTwentyThreeHumidity(s57);

            String s58 = string.substring(348, 350) + "." + string.substring(346, 348);
            System.out.println("前23-24小时室内平均温度为：" + s58 + "℃");
            BigDecimal bigDecimal24 = new BigDecimal(s58);
            equipmentDockingInfo.setTwentyFourHeat(bigDecimal24);

            String s59 = string.substring(350, 352);
            s59 = String.valueOf(Integer.parseInt(s59, 16));
            System.out.println("前23-24小时湿度为：" + s59);
            equipmentDockingInfo.setTwentyFourHumidity(s59);

//            String s60 = string.substring(358, 360) + "." + string.substring(356, 358);
//            System.out.println("前1日0-24小时室内平均温度为：" + s60 + "℃");
//            BigDecimal bigDecimal25 = new BigDecimal(s60);
//            equipmentDockingInfo.setDayHeat(bigDecimal25);

            String s61 = string.substring(360, 362);
            s61 = String.valueOf(Integer.parseInt(s61, 16));
            System.out.println("前1日0-24小时平均湿度为：" + s61);
            equipmentDockingInfo.setDayHumidity(s61);

            String s62 = string.substring(364, 366) + string.substring(362, 364);
            s62 = String.valueOf(Integer.parseInt(s62, 16));
            System.out.println("上报时间间隔（分钟）为：" + s62 + "分钟");
            equipmentDockingInfo.setUploadCycle(Long.parseLong(s62));

            String s63 = string.substring(368, 370) + string.substring(366, 368);
            s63 = String.valueOf(Integer.parseInt(s63, 16));
            System.out.println("上传延时（分钟）为：" + s63 + "分钟");
            equipmentDockingInfo.setUploadBranch(s63);

            String s64 = string.substring(370, 372);
            s64 = String.valueOf(Integer.parseInt(s64, 16));
            System.out.println("上传延时（秒）为：" + s64 + "秒");
            equipmentDockingInfo.setUploadSecond(s64);

            String s65 = string.substring(378, 380) + string.substring(376, 378);
            s65 = String.valueOf(Integer.parseInt(s65, 16));
            System.out.println("上传总次数为：" + s65 + "次");
            equipmentDockingInfo.setUploadCount(s65);

            String s66 = string.substring(382, 384) + string.substring(380, 382);
            s66 = String.valueOf(Integer.parseInt(s66, 16));
            System.out.println("成功次数为：" + s66 + "次");
            equipmentDockingInfo.setSuccesCount(s66);

            String s67 = string.substring(386, 388) + string.substring(384, 386);
            s67 = String.valueOf(Integer.parseInt(s67, 16));
            int number = Integer.parseInt(s67);
            double result = (double) number / 100;
            s67 = String.valueOf(result);
            System.out.println("温度修正参数为：" + s67);
            equipmentDockingInfo.setTemperatureCorrection(s67);

            String s68 = string.substring(390, 392) + string.substring(388, 390);
            s68 = String.valueOf(Integer.parseInt(s68, 16));
            s68 = String.valueOf(Integer.parseInt(s68, 16));
            int num = Integer.parseInt(s68);
            double res = (double) num / 100;
            s68 = String.valueOf(res);
            System.out.println("湿度修正参数为：" + s68);
            equipmentDockingInfo.setHumidityCorrection(s68);

            String s69 = string.substring(392, 394);
            System.out.println("数据有效性为：" + s69);
            equipmentDockingInfo.setIsValid(s69);

            String s70 = string.substring(394, 396);
            s70 = String.valueOf(Integer.parseInt(s70, 16));
            System.out.println("信号强度为：" + s70);
            equipmentDockingInfo.setSignals(s70);

            String s71 = string.substring(396, 398);
            System.out.println("运营商类型为：" + s71);
            equipmentDockingInfo.setOperatorsType(s71);

            String s72 = string.substring(416, 418) + string.substring(414, 416) + string.substring(412, 414) + string.substring(410, 412)
                    + string.substring(408, 410) + string.substring(406, 408) + string.substring(404, 406) + string.substring(402, 404)
                    + string.substring(400, 402) + string.substring(398, 400);
            System.out.println("SIM卡的ICCID为：" + s72);
            equipmentDockingInfo.setICCID(s72);

            String s73 = string.substring(436, 438) + string.substring(434, 436) + string.substring(432, 434) + string.substring(430, 432)
                    + string.substring(428, 430) + string.substring(426, 428) + string.substring(424, 426) + string.substring(422, 424)
                    + string.substring(420, 422) + string.substring(418, 420);
            s73 = s73.replaceAll("^0+", "");
            System.out.println("模组的IMEI为：" + s73);
            equipmentDockingInfo.setIMEI(s73);

            String s74 = string.substring(440, 442) + string.substring(438, 440);
            s74 = String.valueOf(Integer.parseInt(s74, 16));
            System.out.println("上传数据区块除去状态字的协议版本为：" + s74);
            equipmentDockingInfo.setVersion(s74);

            String s75 = string.substring(444, 446) + string.substring(442, 444);
            s75 = String.valueOf(Integer.parseInt(s75, 16));
            System.out.println("上传数据区块状态字的协议版本为：" + s75);
            equipmentDockingInfo.setVersionState(s75);

            String s76 = string.substring(448, 450) + string.substring(446, 448);
            s76 = String.valueOf(Integer.parseInt(s76, 16));
            int numbers = Integer.parseInt(s76);
            s76 = String.format("%02d", numbers);
            System.out.println("上传参数区块的类型为：" + s76);
            equipmentDockingInfo.setType(s76);

            String s77 = string.substring(450, 452) + string.substring(452, 454);
            System.out.println("上传参数区块的特征符号为：" + s77);
            equipmentDockingInfo.setFeatures(s77);

            String s78 = string.substring(454, 456);
            s78 = String.valueOf(Integer.parseInt(s78, 16));
            System.out.println("上传参数区块的长度为：" + s78 + "u");
            equipmentDockingInfo.setLength(s78);

//            String s79 = string.substring(456, 458);
//            s79 = String.valueOf(Integer.parseInt(s79, 16));
//            System.out.println("上传参数区块的校验码为：" + s79);
//            equipmentDockingInfo.setVerificationCode(s79);

            //仪表编号（设备id）
            String meterCode = equipmentDockingInfo.getNodeId();
            //查询该设备的设备信息
            EquipmentInfo equipmentInfo = equipmentInfoMapper.selectEquipmentInfoByNodeId(imei);
            //查询该设备绑定的房间编号
            String roomNo = equipmentInfo.getRoomNo();
            //根据房间编号查询房间信息，带入到采集的实时数据
            RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(roomNo);
            //给采集的信息赋予相关基础信息（小区、楼栋、房间信息等）
            equipmentDockingInfo.setRoomNo(equipmentInfo.getRoomNo());
            equipmentDockingInfo.setVillageName(equipmentInfo.getCommunityName());
            equipmentDockingInfo.setBuildingName(equipmentInfo.getBuildingName());
            equipmentDockingInfo.setUnitName(equipmentInfo.getUnitName());
            equipmentDockingInfo.setRoomName(equipmentInfo.getRoomAme());
            equipmentDockingInfo.setUserName(roomInfo.getPersonName());
            equipmentDockingInfo.setTelephone(roomInfo.getPhone());
            equipmentDockingInfo.setRoomType(roomInfo.getRoomsType());
            equipmentDockingInfo.setLocation(roomInfo.getInstall());
            equipmentDockingInfo.setSignalstrength(Long.valueOf(s70));
            equipmentDockingInfo.setUploadtime(new Date());
            equipmentDockingInfo.setManufactor("博瑞达");
            equipmentDockingInfo.setCreateTime(new Date());
            equipmentDockingInfo.setDeviceStatus("正常");//todo 判断设备状态是否正常（未定）
            equipmentDockingInfo.setDeviceState("正常");//todo  判断维修状态是否正常（未定）
            //供暖状态判断
            if (roomInfo.getHomeType()==null){
                equipmentDockingInfo.setRoomState("0");
            }else if (roomInfo.getHomeType().equals("4")){
                equipmentDockingInfo.setRoomState("1");
            }else {
                equipmentDockingInfo.setRoomState("0");
            }
//            equipmentDockingInfo.setRoomState("正常");

            equipmentDockingInfo.setHistory("1");

            //判断是否存在该表的上一次数据
            List<EquipmentDocking> equipmentDocking1 = equipmentDockingMapper.selectEquipmentDockingByNodeCodes(imei);
            if (equipmentDocking1 != null) {
                //若存在 将数据变更为历史数据
                for (EquipmentDocking equipmentDocking : equipmentDocking1) {
                    equipmentDockingMapper.updateEquipmentDockingHistory(equipmentDocking.getId());
                }

            }
            //将读取到的数据入库(数据采集的信息)
            equipmentDockingService.insertEquipmentDocking(equipmentDockingInfo);
        } catch (Exception e) {
            System.err.println("Failed to parse JSON or decode Base64.");
            e.printStackTrace();
        }




//        } catch (Exception e) {
//            e.printStackTrace();
//            System.err.println("Failed to parse JSON or decode Base64.");
//        }


    }


    @PostMapping("/receivesData")
    public void receivesData(@RequestBody String payload) {
        //黑蚂蚁室温采集器解码规则
        System.out.println("接收到黑蚂蚁室温采集器的数据为：" + payload);
        // 将JSON字符串解析为JSONObject
        JSONObject jsonObj = new JSONObject(payload);

        // 输出各个参数
//        System.out.println("upPacketSN: " + jsonObj.getInt("upPacketSN"));
//        System.out.println("upDataSN: " + jsonObj.getInt("upDataSN"));
//        System.out.println("topic: " + jsonObj.getString("topic"));
//        long timestamp = jsonObj.getLong("timestamp");
//        Date date = new Date(timestamp);
//        System.out.println("上报时间-->"+date);
//        System.out.println("tenantId: " + jsonObj.getString("tenantId"));
//        System.out.println("serviceId: " + jsonObj.getString("serviceId"));
//        System.out.println("protocol: " + jsonObj.getString("protocol"));
//        System.out.println("productId: " + jsonObj.getString("productId"));
//        System.out.println("messageType: " + jsonObj.getString("messageType"));
//        System.out.println("deviceType: " + jsonObj.getString("deviceType"));
//        System.out.println("设备ID-->deviceId: " + jsonObj.getString("deviceId"));
//        System.out.println("assocAssetId: " + jsonObj.getString("assocAssetId"));
//        System.out.println("IMSI: " + jsonObj.getString("IMSI"));
//        System.out.println("IMEI: " + jsonObj.getString("IMEI"));

        // 输出payload中的数据
//        JSONObject payloads = jsonObj.getJSONObject("payload");
//        System.out.println("电压-->VOLTAGE: " + payloads.getDouble("VOLTAGE"));
//        System.out.println("版本号-->VERSION: " + payloads.getString("VERSION"));
//        System.out.println("上传间隔时间(分)-->UPTIME: " + payloads.getLong("UPTIME"));
//        System.out.println("室内温度-->TEMP: " + payloads.getDouble("TEMP"));
//        System.out.println("ICCID-->SN: " + payloads.getString("SN"));
//        System.out.println("室内湿度-->HUMIDITY: " + payloads.getInt("HUMIDITY"));
//        System.out.println("通信串号-->CGSN: " + payloads.getString("CGSN"));

        //解析payload并进行实际的业务处理，保存到数据库
        EquipmentDocking equipmentDockingInfo = new EquipmentDocking();
        //上报时间
        equipmentDockingInfo.setUploadtime(new Date());
        //设备ID
//        equipmentDockingInfo.setNodeId(jsonObj.getString("deviceId"));
        //IMEI
        equipmentDockingInfo.setIMEI(jsonObj.getString("IMEI"));
        //电压
//        double voltage = payloads.getDouble("VOLTAGE");
//        BigDecimal bigDecimal = new BigDecimal(voltage);
//        equipmentDockingInfo.setVoltage(bigDecimal);
        //版本号
//        equipmentDockingInfo.setVer(payloads.getString("VERSION"));
        //上传间隔时间(分)
//        equipmentDockingInfo.setUploadCycle(payloads.getLong("UPTIME"));
        //室内温度
//        double temp = payloads.getDouble("TEMP");
//        BigDecimal bigDecimal1 = new BigDecimal(temp);
//        equipmentDockingInfo.setTemp(bigDecimal1);

        // 获取并解析 payload 对象中的内容
        Object payloadObjs = jsonObj.get("payload");
        if (payloadObjs instanceof JSONObject) {
            JSONObject payloadObj = jsonObj.getJSONObject("payload");
            String payloadServiceId = payloadObj.getString("serviceId");

            // 获取 serviceData 对象中的内容
            JSONObject serviceDataObj = payloadObj.getJSONObject("serviceData");
            String uData = serviceDataObj.getString("uData");

            // Optional field TEMP
            double temp = serviceDataObj.has("TEMP") ? serviceDataObj.getDouble("TEMP") : 0.0;
            equipmentDockingInfo.setTemp(BigDecimal.valueOf(Double.parseDouble(String.valueOf(temp))));
        }else {
            equipmentDockingInfo.setTemp(BigDecimal.valueOf(0));
        }


        //ICCID
//        equipmentDockingInfo.setICCID(payloads.getString("SN"));
        //室内湿度
//        equipmentDockingInfo.setHumi(new BigDecimal(payloads.getInt("HUMIDITY")));

        //仪表编号（设备id）
        String meterCode = equipmentDockingInfo.getIMEI();
        //查询该设备的设备信息
        EquipmentInfo equipmentInfo = equipmentInfoMapper.selectEquipmentInfoByNodeId(meterCode);
        //查询该设备绑定的房间编号
        String roomNo = equipmentInfo.getRoomNo();
        //根据房间编号查询房间信息，带入到采集的实时数据
        RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(roomNo);
        //给采集的信息赋予相关基础信息（小区、楼栋、房间信息等）
        equipmentDockingInfo.setRoomNo(equipmentInfo.getRoomNo());
        equipmentDockingInfo.setVillageName(equipmentInfo.getCommunityName());
        equipmentDockingInfo.setBuildingName(equipmentInfo.getBuildingName());
        equipmentDockingInfo.setUnitName(equipmentInfo.getUnitName());
        equipmentDockingInfo.setRoomName(equipmentInfo.getRoomAme());
        equipmentDockingInfo.setUserName(roomInfo.getPersonName());
        equipmentDockingInfo.setTelephone(roomInfo.getPhone());
        equipmentDockingInfo.setRoomType(roomInfo.getRoomsType());
        equipmentDockingInfo.setLocation(roomInfo.getInstall());
//        equipmentDockingInfo.setSignalstrength(Long.valueOf(s70));
        equipmentDockingInfo.setUploadtime(new Date());
        equipmentDockingInfo.setManufactor("黑蚂蚁.");
        equipmentDockingInfo.setCreateTime(new Date());
        equipmentDockingInfo.setDeviceStatus("正常");//todo 判断设备状态是否正常（未定）
        equipmentDockingInfo.setDeviceState("正常");//todo  判断维修状态是否正常（未定）
        equipmentDockingInfo.setRoomState("正常");
        equipmentDockingInfo.setHistory("1");

        //判断是否存在该表的上一次数据
        EquipmentDocking equipmentDocking1 = equipmentDockingMapper.selectEquipmentDockingByNodeCode(meterCode);
        if (equipmentDocking1 != null) {
            //若存在 将数据变更为历史数据
            equipmentDockingMapper.updateEquipmentDockingHistory(equipmentDocking1.getId());
        }
        //将读取到的数据入库(数据采集的信息)
        equipmentDockingService.insertEquipmentDocking(equipmentDockingInfo);
        System.out.println("新增成功！！！");
    }

    /**
     * 接收黑蚂蚁厂家推送室温采集器数据
     * @param dataList
     * @return
     */
    @PostMapping("/ReceiveRtValve")
    public Map<String, Object> receiveSensorData(@RequestBody String dataList) {
        System.err.println("接收到的数组数据为：-----------------"+dataList+"-------------------");
        Map<String, Object> response = new  LinkedHashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 将JSON字符串解析为数组
            JsonNode jsonArray = objectMapper.readTree(dataList);
            // 遍历数组处理每个元素
            for (JsonNode jsonNode : jsonArray) {
                System.err.println("接收到的单条数据为：-----------------"+jsonNode);
                          // 提取参数
             String nodeId = jsonNode.get("nodeid").asText();//设备 id
             String deviceId = jsonNode.get("device_ID").asText(); //设备 ID
             float temp = jsonNode.get("temp").floatValue();// 温度
             float humi = jsonNode.get("humi").floatValue(); // 湿度
             int signalStrength = jsonNode.get("signalstrength").asInt(); // 信号强度
             float batteryVol = jsonNode.get("battery_VOL").floatValue(); // 电池电压
             String sampleTime = jsonNode.get("sampletime").asText(); //采样时间
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date parse = df.parse(sampleTime);
                // 输出解析后的数据以验证
             System.out.println("设备 ID: " + nodeId);
            System.out.println("设备 ID: " + deviceId);
            System.out.println("温度: " + temp);
            System.out.println("湿度: " + humi);
            System.out.println("信号强度: " + signalStrength);
            System.out.println("电池电压: " + batteryVol);
            System.out.println("采样时间: " + sampleTime);
            //将接收到的额数据存储至数据库
            EquipmentDocking equipmentDockingInfo = new EquipmentDocking();
            //赋值设备ID
            equipmentDockingInfo.setNodeId(nodeId);
            insertsEquipmentDocking(equipmentDockingInfo);
            EquipmentInfo equipmentInfo = equipmentInfoMapper.selectEquipmentInfoByNodeId(nodeId);
                //判断是否存在该表的上一次数据
                EquipmentDocking equipmentDocking1 = equipmentDockingMapper.selectEquipmentDockingByNodeCode(nodeId);
                //对于小区名称为十三房舍  电务  机务段东门楼的小区数据不予持久化
                if (equipmentInfo.getCommunityName().equals("十三房舍")||equipmentInfo.getCommunityName().equals("电务")
                        ||equipmentInfo.getCommunityName().equals("机务段东门楼")){

                }else {
                    //每次进行新数据存储时，将上一次拉取的不是垃圾的数据设置为历史数据
//                if (equipmentDocking1!=null&&!equipmentDocking1.getUploadtime().equals(equipmentDocking.getUploadtime())){
                    if (equipmentDocking1!=null){
                        Date uploadTime1 = equipmentDocking1.getUploadtime();
                        // 将 Date 转换为 Instant
                        Instant instant1 = uploadTime1.toInstant();
                        Instant instant2 = parse.toInstant();
                        Date date = new Date();
                        Instant instant = date.toInstant();//当前时间
                        // 计算两个时间点之间的差异
                        long hoursDifference = Duration.between(instant1, instant2).toHours();
                        long hoursDifferences = Duration.between(instant2, instant).toHours();//当前时间与上次上传时间的间隔
                        //两次上传时间相等 但是设备是在线的（可能是设备上传周期大于一小时）
                        if (equipmentDocking1.getUploadtime().equals(parse)&&hoursDifferences<=24){
//                            equipmentDockingMapper.updateEquipmentDockingHistory(equipmentDocking1.getId());
//                           equipmentDockingMapper.insertEquipmentDocking(equipmentDockingInfo);
                            //两次上传时间不同 证明设备在正常上传数据
                        }else if (!equipmentDocking1.getUploadtime().equals(parse)){
//                            equipmentDockingMapper.updateEquipmentDockingHistory(equipmentDocking1.getId());
//                            equipmentDockingMapper.insertEquipmentDocking(equipmentDockingInfo);                            //两次上传时间相同 但是上传时间不是24小时之内的 视为掉线设备  将它的上传时间改为这一次的上传时间
                        }else if (equipmentDocking1.getUploadtime().equals(parse)&&hoursDifferences>24){
//                            equipmentDockingMapper.updateEquipmentDockingHistorys(equipmentDocking1.getId(),equipmentDocking1.getUploadtime());
                        }

                    }else{//第一次插入数据
//                        equipmentDockingMapper.insertEquipmentDocking(equipmentDockingInfo);

                    }

                }


//            if (equipmentInfo != null) {
//                if (equipmentInfo.getCommunityName().equals("十三房舍")||equipmentInfo.getCommunityName().equals("电务")
//                        ||equipmentInfo.getCommunityName().equals("机务段东门楼")){
//
//                }else {
//                    //查询该设备绑定的房间编号
//                    String roomNo = equipmentInfo.getRoomNo();
//                    //根据房间编号查询房间信息，带入到采集的实时数据
//                    RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(roomNo);
//                    //给采集的信息赋予相关基础信息（小区、楼栋、房间信息等）
//                    equipmentDockingInfo.setRoomNo(equipmentInfo.getRoomNo());
//                    equipmentDockingInfo.setVillageName(equipmentInfo.getCommunityName());
//                    equipmentDockingInfo.setBuildingName(equipmentInfo.getBuildingName());
//                    equipmentDockingInfo.setUnitName(equipmentInfo.getUnitName());
//                    equipmentDockingInfo.setRoomName(equipmentInfo.getRoomAme());
//                    equipmentDockingInfo.setUserName(roomInfo.getPersonName());
//                    equipmentDockingInfo.setTelephone(roomInfo.getPhone());
//                    equipmentDockingInfo.setRoomType(roomInfo.getRoomsType());
//                    equipmentDockingInfo.setLocation(roomInfo.getInstall());
////        equipmentDockingInfo.setSignalstrength(Long.valueOf(s70));
//                    equipmentDockingInfo.setUploadtime(parse);
//                    equipmentDockingInfo.setManufactor("黑蚂蚁");
//                    equipmentDockingInfo.setCreateTime(new Date());
//                    equipmentDockingInfo.setDeviceStatus("正常");//todo 判断设备状态是否正常（未定）
//                    equipmentDockingInfo.setDeviceState("正常");//todo  判断维修状态是否正常（未定）
//                    equipmentDockingInfo.setRoomState("正常");
//                    equipmentDockingInfo.setHistory("1");
//                    equipmentDockingInfo.setNodeId(nodeId);
//                    //室温
//                    equipmentDockingInfo.setTemp(BigDecimal.valueOf(temp));
//                    //湿度
//                    equipmentDockingInfo.setHumi(BigDecimal.valueOf(humi));
//                    //信号强度
//                    equipmentDockingInfo.setSignalstrength((long) signalStrength);
//
//                //判断是否存在该表的上一次数据
//                EquipmentDocking equipmentDocking1 = equipmentDockingMapper.selectEquipmentDockingByNodeCode(nodeId);
//                if (equipmentDocking1 != null) {
//                    //若存在 将数据变更为历史数据
//                    equipmentDockingMapper.updateEquipmentDockingHistory(equipmentDocking1.getId());
//                }
//                //将读取到的数据入库(数据采集的信息)
//                equipmentDockingService.insertEquipmentDocking(equipmentDockingInfo);
//                }
                }


            response.put("IsSuccess", true);
            response.put("Msg", "操作成功");
        } catch (Exception e) {
            response.put("IsSuccess", false);
            response.put("Msg", "Error processing data: " + e.getMessage());
        }
        return response;



//        try {
//            // 将 JSON 字符串解析为
//             JsonNode jsonNode  = objectMapper.readTree(dataList);
//            // 提取参数
//             String nodeId = jsonNode.get("nodeid").asText();//设备 id
//             String deviceId = jsonNode.get("device_ID").asText(); //设备 ID
//             float temp = jsonNode.get("temp").floatValue();// 温度
//             float humi = jsonNode.get("humi").floatValue(); // 湿度
//             int signalStrength = jsonNode.get("signalstrength").asInt(); // 信号强度
//             float batteryVol = jsonNode.get("battery_VOL").floatValue(); // 电池电压
//             String sampleTime = jsonNode.get("sampletime").asText(); //采样时间
//            // 输出解析后的数据以验证
//             System.out.println("设备 ID: " + nodeId);
//            System.out.println("设备 ID: " + deviceId);
//            System.out.println("温度: " + temp);
//            System.out.println("湿度: " + humi);
//            System.out.println("信号强度: " + signalStrength);
//            System.out.println("电池电压: " + batteryVol);
//            System.out.println("采样时间: " + sampleTime);
//            //将接收到的额数据存储至数据库
//            EquipmentDocking equipmentDockingInfo = new EquipmentDocking();
//            EquipmentInfo equipmentInfo = equipmentInfoMapper.selectEquipmentInfoByNodeId(nodeId);
//            if (equipmentInfo != null) {
//               //查询该设备绑定的房间编号
//        String roomNo = equipmentInfo.getRoomNo();
//        //根据房间编号查询房间信息，带入到采集的实时数据
//        RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(roomNo);
//        //给采集的信息赋予相关基础信息（小区、楼栋、房间信息等）
//        equipmentDockingInfo.setRoomNo(equipmentInfo.getRoomNo());
//        equipmentDockingInfo.setVillageName(equipmentInfo.getCommunityName());
//        equipmentDockingInfo.setBuildingName(equipmentInfo.getBuildingName());
//        equipmentDockingInfo.setUnitName(equipmentInfo.getUnitName());
//        equipmentDockingInfo.setRoomName(equipmentInfo.getRoomAme());
//        equipmentDockingInfo.setUserName(roomInfo.getPersonName());
//        equipmentDockingInfo.setTelephone(roomInfo.getPhone());
//        equipmentDockingInfo.setRoomType(roomInfo.getRoomsType());
//        equipmentDockingInfo.setLocation(roomInfo.getInstall());
////        equipmentDockingInfo.setSignalstrength(Long.valueOf(s70));
//        equipmentDockingInfo.setUploadtime(new Date());
//        equipmentDockingInfo.setManufactor("黑蚂蚁.");
//        equipmentDockingInfo.setCreateTime(new Date());
//        equipmentDockingInfo.setDeviceStatus("正常");//todo 判断设备状态是否正常（未定）
//        equipmentDockingInfo.setDeviceState("正常");//todo  判断维修状态是否正常（未定）
//        equipmentDockingInfo.setRoomState("正常");
//        equipmentDockingInfo.setHistory("1");
//        equipmentDockingInfo.setNodeId(nodeId);
//        //室温
//        equipmentDockingInfo.setTemp(BigDecimal.valueOf(temp));
//        //湿度
//        equipmentDockingInfo.setHumi(BigDecimal.valueOf(humi));
//        //信号强度
//        equipmentDockingInfo.setSignalstrength((long) signalStrength);
//
//            }else {
//                equipmentDockingInfo.setRoomNo("待定");
//                equipmentDockingInfo.setVillageName("待定");
//                equipmentDockingInfo.setBuildingName("待定");
//                equipmentDockingInfo.setUnitName("待定");
//                equipmentDockingInfo.setRoomName("待定");
//                equipmentDockingInfo.setUserName("待定");
//                equipmentDockingInfo.setTelephone("待定");
//                equipmentDockingInfo.setRoomType("待定");
//                equipmentDockingInfo.setLocation("待定");
////        equipmentDockingInfo.setSignalstrength(Long.valueOf(s70));
//                equipmentDockingInfo.setUploadtime(new Date());
//                equipmentDockingInfo.setManufactor("黑蚂蚁.");
//                equipmentDockingInfo.setCreateTime(new Date());
//                equipmentDockingInfo.setDeviceStatus("正常");//todo 判断设备状态是否正常（未定）
//                equipmentDockingInfo.setDeviceState("正常");//todo  判断维修状态是否正常（未定）
//                equipmentDockingInfo.setRoomState("正常");
//                equipmentDockingInfo.setHistory("1");
//                //室温
//                equipmentDockingInfo.setTemp(BigDecimal.valueOf(temp));
//                //湿度
//                equipmentDockingInfo.setHumi(BigDecimal.valueOf(humi));
//                //信号强度
//                equipmentDockingInfo.setSignalstrength((long) signalStrength);
//            }
//            //判断是否存在该表的上一次数据
//            EquipmentDocking equipmentDocking1 = equipmentDockingMapper.selectEquipmentDockingByNodeCode(nodeId);
//            if (equipmentDocking1 != null) {
//                //若存在 将数据变更为历史数据
//                equipmentDockingMapper.updateEquipmentDockingHistory(equipmentDocking1.getId());
//            }
//            //将读取到的数据入库(数据采集的信息)
////            equipmentDockingService.insertEquipmentDocking(equipmentDockingInfo);
//            System.out.println("新增成功！！！");
////            Response apiResponse = new Response(true, "操作成功");
////            response.put("Response", apiResponse);
//            response.put("IsSuccess", true);
//            response.put("Msg", "操作成功");
//        } catch (Exception e) {
////            Response apiResponse = new Response(false, "处理数据时出错: " + e.getMessage());
////            response.put("Response", apiResponse);
//            response.put("IsSuccess", false);
//            response.put("Msg", "Error processing data: " + e.getMessage());
//        }
//        return response;
    }

    private void insertsEquipmentDocking(EquipmentDocking equipmentDocking) {
        //根据设备ID查询对应的基础信息，从中获取小区、楼栋、单元、门牌号
        //todo
        EquipmentInfo equipmentInfo = equipmentInfoMapper.selectEquipmentInfoByNodeId(equipmentDocking.getNodeId());
        if (equipmentInfo != null) {
            RoomInfo roomInfo = roomInfoMapper.selectRoomInfoByRoomNo(equipmentDocking.getRoomNo());
            if (roomInfo != null) {
                //小区
                equipmentDocking.setVillageName(roomInfo.getCommunityName());
                //楼栋
                equipmentDocking.setBuildingName(roomInfo.getBuildingName());
                //单元
                equipmentDocking.setUnitName(roomInfo.getUnitName());
                //门牌号
                equipmentDocking.setRoomName(roomInfo.getBuildingName()+"-"+roomInfo.getUnitName()+"-"+roomInfo.getHouseNumber());
                //房间编号
                equipmentDocking.setRoomNo(roomInfo.getRoomNo());
            }else {
                //小区
                equipmentDocking.setVillageName(equipmentInfo.getCommunityName());
                //楼栋
                equipmentDocking.setBuildingName(equipmentInfo.getBuildingName());
                //单元
                equipmentDocking.setUnitName(equipmentInfo.getUnitName());
                //门牌号
                equipmentDocking.setRoomName(equipmentInfo.getBuildingName()+"-"+equipmentInfo.getUnitName()+"-"+equipmentInfo.getRoomAme());
                //房间编号
                equipmentDocking.setRoomNo(equipmentInfo.getRoomNo());

            }
        }
        if (equipmentDocking.getDeviceStatus()==null){
            equipmentDocking.setDeviceStatus("正常");
        }
        equipmentDocking.setRoomState("0");
        equipmentDocking.setHistory("1");
        equipmentDocking.setManufactor("黑蚂蚁");
//        equipmentDockingMapper.insertEquipmentDocking(equipmentDocking);

    }


    public static void main(String[] args) {
//        String payload = "{\"upPacketSN\":-1,\"upDataSN\":-1,\"topic\":\"v1/up/ad19prof\",\"timestamp\":1727322982670,\"tenantId\":\"2000092468\",\"serviceId\":\"WaterMeter\",\"protocol\":\"lwm2m\",\"profile\":true,\"productId\":\"16998316\",\"payload\":{\"serviceId\":\"WaterMeter\",\"serviceData\":{\"uData\":\"/v7+aEY3eXRZIDJhgdSQIAEAAGAjAAAAAGAjAAAAABJgIwAAAAAAAAAAAAATVhEmCSQEAAAAAFUjAAAAVyMAAABgIwAAAGcjAAAAZCMAAABwIwAAAHQjAAAAdCMAAAB2IwAAAIUjAAAAciMAAABoIwAAAHQjAAAAgiMAAACHIwAAAJIjAAAAliMAAAAEJAAAABIkAAAAEiQAAAARJAAAABMkAAAAFSQAAACRIwAAAIcjADwAPAA8PABdD9oNAAAAAAEEABAJFyAAIyMRhok3eXRZIDJhCAAALQMOAAEA//8uc/cW\"}},\"messageType\":\"dataReport\",\"deviceType\":\"\",\"deviceId\":\"e5f8c7d60f4f425eb0965a330194ea05\",\"assocAssetId\":\"\",\"IMSI\":\"undefined\",\"IMEI\":\"861322059747937\"}";
        String payload = "{\"upPacketSN\":-1,\"upDataSN\":-1,\"topic\":\"v1/up/ad19prof\",\"timestamp\":1727326004831,\"tenantId\":\"2000092468\",\"serviceId\":\"WaterMeter\",\"protocol\":\"lwm2m\",\"profile\":true,\"productId\":\"16998316\",\"payload\":{\"serviceId\":\"WaterMeter\",\"serviceData\":{\"uData\":\"/v7+aEZ3N2hZIDJhgdSQIAEAAGgjAAAAAGgjAAAAAFlgIwAAAAAAAAAAAAA3RhImCSQJAAAAAEgjAAAAFCMAAACRIgAAAIIiAAAAISMAAAASIwAAABAjAAAAEyMAAAATIwAAAFgjAAAAiCMAAACIIwAAAIYjAAAAlSMAAAAHJAAAAAkkAAAAJyQAAABDJAAAAFAkAAAARCQAAABBJAAAADQkAAAAISQAAAAAJAAAAAIkADwAPAA8PABeDyIPAAAAAAEHABSXFiAAIyMRhol3N2hZIDJhCAAALQMOAAEA//8uRN4W\"}},\"messageType\":\"dataReport\",\"deviceType\":\"205aa9aa83c94f3a8c720e65fffe646e\",\"assocAssetId\":\"\",\"IMSI\":\"undefined\",\"IMEI\":\"861322059683777\"}";

        try {
            // 解析 JSON 字符串为 JSONObject
            JSONObject jsonObj = new JSONObject(payload);

            // 获取顶层字段的值
            int upPacketSN = jsonObj.getInt("upPacketSN");
            int upDataSN = jsonObj.getInt("upDataSN");
            String topic = jsonObj.getString("topic");
            long timestamp = jsonObj.getLong("timestamp");
            String tenantId = jsonObj.getString("tenantId");
            String serviceId = jsonObj.getString("serviceId");
            String protocol = jsonObj.getString("protocol");
            boolean profile = jsonObj.getBoolean("profile");
            String productId = jsonObj.getString("productId");
            String messageType = jsonObj.getString("messageType");
            String deviceType = jsonObj.getString("deviceType");
//            String deviceId = jsonObj.getString("deviceId");
            String assocAssetId = jsonObj.getString("assocAssetId");
            String IMSI = jsonObj.getString("IMSI");
            String IMEI = jsonObj.getString("IMEI");

            // 打印顶层字段的值
            System.out.println("upPacketSN: " + upPacketSN);
            System.out.println("upDataSN: " + upDataSN);
            System.out.println("topic: " + topic);
            System.out.println("timestamp: " + timestamp);
            System.out.println("tenantId: " + tenantId);
            System.out.println("serviceId: " + serviceId);
            System.out.println("protocol: " + protocol);
            System.out.println("profile: " + profile);
            System.out.println("productId: " + productId);
            System.out.println("messageType: " + messageType);
            System.out.println("deviceType: " + deviceType);
//            System.out.println("deviceId: " + deviceId);
            System.out.println("assocAssetId: " + assocAssetId);
            System.out.println("IMSI: " + IMSI);
            System.out.println("IMEI: " + IMEI);

            // 获取并解析 payload 对象中的内容
            JSONObject payloadObj = jsonObj.getJSONObject("payload");
            String payloadServiceId = payloadObj.getString("serviceId");

            // 获取 serviceData 对象中的内容
            JSONObject serviceDataObj = payloadObj.getJSONObject("serviceData");
            String uData = serviceDataObj.getString("uData");

            // Optional field TEMP
            double temp = serviceDataObj.has("TEMP") ? serviceDataObj.getDouble("TEMP") : 0.0;

            // 打印 payload 和 serviceData 字段的值
            System.out.println("Payload serviceId: " + payloadServiceId);
            System.out.println("uData: " + uData);
            System.out.println("TEMP: " + temp);


        } catch (JSONException e) {
            System.err.println("JSON 解析错误: " + e.getMessage());
        }
    }
}
